'''
Created on Aug 12, 2010

@author: behrooz
'''

from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from amscms.ams.models import Ad, Advertizer, AdPricing
from django.db.models.aggregates import Count
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from amscms.core.templatetags.jalali_view import gregorian_to_jalali

class AdvertizerAdmin(ModelAdmin):
    list_display = ('id', 'user', 'type', 'description', 'count_ads', 'link_view_ads')
    list_filter = ('type', )
    search_fields = ['type', 'description', 'user__first_name', 'user__email', 'user__last_name']
    
    def count_ads(self, obj):
        result = Advertizer.objects.filter(ad__advertizer=obj).annotate(ads=Count("ad__id"))
        if result is None or len(result) == 0:
            return "0"
        return str(result[0].ads)
    count_ads.short_description = _("Count")
    
    def link_view_ads(self, obj):
        return mark_safe('<a href="/ads/explore/advertizer/%s/" target="_blank">%s</a>' % (obj.id, _("Ads")))
    link_view_ads.allow_tags = True
    link_view_ads.short_description = _("View") 
    
class AdAdmin(ModelAdmin):
    list_display = ('id', 'enabled', 'title', 'advertizer', 'j_registration_date', 'j_start_date', 'j_end_date')
    exclude = ('stats', )
    list_filter = ('enabled', 'registration_date', 'start_date', 'end_date')
    search_fields = ['title', 'description', 'advertizer__user__first_name', 'advertizer__user__email', 'advertizer__user__last_name']
    ordering = ("-start_date", )
    
    def j_registration_date(self, obj):
        return gregorian_to_jalali(obj.registration_date)
    j_registration_date.short_description = _("Registration Date")
    
    def j_start_date(self, obj):
        return gregorian_to_jalali(obj.start_date)
    j_start_date.short_description = _("Publish Start Date")
    
    def j_end_date(self, obj):
        return gregorian_to_jalali(obj.end_date)
    j_end_date.short_description = _("Publish End Date")
    
class AdPricingAdmin(ModelAdmin):
    list_display = ('id', 'is_default', 'enabled', 'daily_rate', 
                    'min_days_discount', 'min_days_discount_forevery', 'min_days_discount_rate',
                    'range_discount_start', 'range_discount_end', 'range_discount_forevery', 'range_discount_rate')
    list_filter = ("enabled", "is_default")
    ordering = ("-is_default", "-enabled", )
    
# Admin Registration
admin.site.register(Ad, AdAdmin)
admin.site.register(Advertizer, AdvertizerAdmin)
admin.site.register(AdPricing, AdPricingAdmin)
